/*
 * $Id$
 */
package py.windmill.resolution;

import java.util.HashMap;
import java.util.Map;

import py.windmill.action.Request;
import py.windmill.action.ValidationErrors;

/**
 *
 * @author myang
 */
public abstract class Tiles extends HTML {

    public static final String TILES = "__ff_tiles__";

    public static final String TILES_TEMPLATE = "__ff_tiles_template__";

    private String _template;

    /**
     * 
     */
    public Tiles() {
        this(null);
    }

    /**
     * 
     * @param page 
     */
    public Tiles(final String template) {
        super();
        _template = template;
    }

    /**
     * 
     * @param template
     * @param charset 
     */
    public Tiles(final String template, final String charset) {
        super(charset);
        _template = template;
    }

    /**
     * 
     * @param req
     * @param val
     */
    @Override
    public void execute(final Request req, final Object val) {
        execute(req, prepare(req, val));
    }

    @Override
    public void onErrors(final Request req, final ValidationErrors errors) {
        execute(req, prepare(req, errors));
    }

    /**
     * 
     * @param req
     * @param tm 
     */
    private void execute(final Request req, final TilesMap tm) {
        req.attr(TILES, tm.map()).forward(template(req));
    }

    /**
     * 
     * @param m
     * @param val 
     */
    public abstract TilesMap prepare(Request req, Object val);

    /**
     * 
     * @param m
     * @param errors 
     */
    public TilesMap prepare(final Request req, final ValidationErrors errors) {
        return prepare(req, (Object)errors);
    }

    /**
     * 
     * @param req
     * @return 
     */
    private String template(final Request req) {
        final String s = 
          (_template == null ? (String)req.context(TILES_TEMPLATE) : _template);
        if (null == s) {
            throw new RuntimeException("no template");
        }
        return s;
    }
}
